/**
* CPAINT (Cross-Platform Asynchronous INterface Toolkit) - Version 2
*
* http://sf.net/projects/cpaint
* 
* released under the terms of the GPL
* see http://www.fsf.org/licensing/licenses/gpl.txt for details
*
* @package    CPAINT
* @author     Paul Sullivan <wiley14@gmail.com>
* @author     Dominique Stender <dstender@st-webdevelopment.de>
* @copyright  Copyright (c) 2005-2006 Paul Sullivan, Dominique Stender - http://sf.net/projects/cpaint
*/
	var timeIndex 		= 0;
	var refreshInterval	= 1000;
	var chat_line		= false;
	var chat_nickname	= false;
	var chat_history	= false;
	var chat_subscriber_list= false;

	// initialize cpaint
  var cp = new cpaint();
  cp.set_transfer_mode('post');
  cp.set_response_type('object');
  cp.set_persistent_connection(true);
  cp.set_async(true);
  cp.set_proxy_url('');
  cp.set_debug(0);

	function chat() {

		if (chat_line.value != '') {
			cp.call('chat.php', 'chat', chatClean, timeIndex, current_nickname, chat_line.value);
		}

		return false;
	}

	function chatClean(result) {
		chat_line.value = '';
		chat_line.focus();
	}

	function requestHistory() {
  	cp.call('chat.php', 'retrieveHistory', retrieveHistory, timeIndex, current_nickname);
	}

	function retrieveHistory(result) {

		if (result != null) {
			// assign new time
			timeIndex = result.ajaxResponse[0].find_item_by_id('result', 'timeindex').data;

			// append new lines to history
			var lineCount	= 0;
			var lines	= result.ajaxResponse[0].find_item_by_id('result', 'lines');

			if (lines.line) {
				lineCount = lines.line.length;
			}

			for (var i = 0; i < lineCount; i++) {
				var line_date = new Date();
				line_date.setTime(1000 * Math.round(lines.line[i].time[0].data));
	
				chat_history.value = "("
						+ sprintf('%02d', line_date.getHours()) + ':' 
						+ sprintf('%02d', line_date.getMinutes()) + ':' 
						+ sprintf('%02d', line_date.getSeconds()) + ') '
						+ lines.line[i].nickname[0].data
						+ ": "
						+ lines.line[i].text[0].data
						+ "\n"
						+ chat_history.value;
			}

			// update subscribers
			var subscribers_node	= result.ajaxResponse[0].find_item_by_id('result', 'subscribers');
                        var subscribers         = '';

                        for (var i = 0; i < subscribers_node.subscriber.length; i++) {
                                subscribers += subscribers_node.subscriber[i].data + "\n";
                        }

                        chat_subscriber_list.value = subscribers;
		}
	}

	function requestSubscribers() {
		cp.call('chat.php', 'retrieveSubscribers', retrieveSubscribers);
	}

	function retrieveSubscribers(result) {
		if (result != null) {
			var subscribers_node	= result.ajaxResponse[0].find_item_by_id('result', 'subscribers');
			var subscribers		= '';
	
			for (var i = 0; i < subscribers_node.subscriber.length; i++) {
				subscribers += subscribers_node.subscriber[i].data + "\n";
			}

			chat_subscriber_list.value = subscribers;
		}
	}

	function requestNicknameChange() {
		if (chat_nickname.value != '' && chat_nickname.value != current_nickname) {
			cp.call('chat.php', 'changeNickname', retrieveNickname, current_nickname, chat_nickname.value);
		}
	}

	function retrieveNickname(result) {
		var nickname = current_nickname;

		if (result != null) {
			nickname		= result.ajaxResponse[0].find_item_by_id('result', 'namechange').nick[0].data;

			if (nickname == current_nickname) {
				alert("some error occurred while changing your nickname\nmaybe the nickname is already taken?");
			}
		}
	
		current_nickname	= nickname
		chat_nickname.value	= nickname;
	}

	// borrowed this from somewhere
	function sprintf() {
		if (!arguments || arguments.length < 1 || !RegExp)
		{
		return;
		}
		var str = arguments[0];
		var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
		var a = b = [], numSubstitutions = 0, numMatches = 0;
		while (a = re.exec(str))
		{
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];
		
		numMatches++;
		if (pType == '%')
		{
			subst = '%';
		}
		else
		{
			numSubstitutions++;
			if (numSubstitutions >= arguments.length)
			{
			alert('Error! Not enough function arguments (' + (arguments.length - 1)
			+ ', excluding the string)\n'
			+ 'for the number of substitution parameters in string ('
			+ numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			var pad = '';
				if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			else if (pPad) pad = pPad;
			var justifyRight = true;
				if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
				if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
				if (pPrecision && pType == 'f')
				precision = parseInt(pPrecision.substring(1));
			var subst = param;
			switch (pType)
			{
			case 'b':
			subst = parseInt(param).toString(2);
			break;
			case 'c':
			subst = String.fromCharCode(parseInt(param));
			break;
			case 'd':
			subst = parseInt(param) ? parseInt(param) : 0;
			break;
			case 'u':
			subst = Math.abs(param);
			break;
			case 'f':
			subst = (precision > -1)
			? Math.round(parseFloat(param) * Math.pow(10, precision))
			/ Math.pow(10, precision)
			: parseFloat(param);
			break;
			case 'o':
			subst = parseInt(param).toString(8);
			break;
			case 's':
			subst = param;
			break;
			case 'x':
			subst = ('' + parseInt(param).toString(16)).toLowerCase();
			break;
			case 'X':
			subst = ('' + parseInt(param).toString(16)).toUpperCase();
			break;
			}
			var padLeft = minLength - subst.toString().length;
			if (padLeft > 0)
			{
			var arrTmp = new Array(padLeft+1);
			var padding = arrTmp.join(pad?pad:" ");
			}
			else
			{
			var padding = "";
			}
		}
		str = leftpart + padding + subst + rightPart;
		}
		return str;
	}
	
